package splitframe.farm.serviceutil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DatagramOutputStream extends ByteArrayOutputStream {
	public DatagramOutputStream(DatagramSocket socket, InetAddress address,
			int port) {
		this(socket, address, port, 512);
	}

	DatagramSocket socket;

	DatagramPacket packet;

	public DatagramOutputStream(DatagramSocket socket, InetAddress address,
			int port, int initialSize) {
		super(initialSize);
		this.socket = socket;
		packet = new DatagramPacket(new byte[0], 0, address, port);
	}

	public void flush() throws IOException {
		if (count >= 65508)
			throw new IOException("Packet overflow (" + count + ") bytes");
		/* packet.setData (buf, 0, count); */
		packet.setData(buf);
		packet.setLength(count);
		socket.send(packet);
		reset();
	}
}
